package main

import "C"
import (
	"fmt"
	"github.com/garyburd/redigo/redis"
	"io"
	// "io/ioutil"
	"log"
	"os"
	_ "reflect"
	"strings"
	"sync"
	"time"
)

var (
	Debug   *log.Logger // 记录所有日志
	Info    *log.Logger // 重要的信息
	Warning *log.Logger // 需要注意的信息
	Error   *log.Logger // 非常严重的问题
)

func init() {
	file, err := os.OpenFile("errors.txt",
		os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
	if err != nil {
		log.Fatalln("Failed to open error log file:", err)
	}

	Debug = log.New(io.MultiWriter(file, os.Stdout),
		"DEBUG: ",
		log.Ldate|log.Ltime|log.Lshortfile)

	Info = log.New(io.MultiWriter(file, os.Stdout),
		"INFO: ",
		log.Ldate|log.Ltime|log.Lshortfile)

	Warning = log.New(io.MultiWriter(file, os.Stdout),
		"WARNING: ",
		log.Ldate|log.Ltime|log.Lshortfile)

	Error = log.New(io.MultiWriter(file, os.Stderr),
		"ERROR: ",
		log.Ldate|log.Ltime|log.Lshortfile)
}

/********************************redis库相关*********************************************************************/
var g_c redis.Conn = nil
var g_lock sync.Mutex

//export RedisInit
func RedisInit(pro, host, port string) bool {
	g_lock.Lock()
	defer g_lock.Unlock()
	if g_c != nil {
		g_c.Close()
	}
	var err error = nil
	g_c, err = redis.Dial(pro, host+":"+port)
	if err != nil {
		fmt.Println("Connect to redis error", err)
		g_c = nil
		return false
	}

	return true
}

//export RedisExit
func RedisExit() {
	// Debug.Println("enter RedisExit")
	if g_c != nil {
		g_c.Close()
	}
	g_c = nil
}

//export RedisPut
func RedisPut(app, model, data string) bool {
	// Debug.Println("enter RedisPut app=", app, "model=", model, "data=", data)
	g_lock.Lock()
	defer g_lock.Unlock()
	if g_c == nil {
		Debug.Println("g_c is nil")
		return false
	}
	_, err := g_c.Do("lpush", app, model+"="+data)
	if err != nil {
		Debug.Println("redis set failed:", err)
		return false
	}

	return true
}

//export RdisGet
func RdisGet(app string) string {
	vals, err := g_c.Do("rpop", app)
	if err == nil && vals != nil {
		str := string(vals.([]uint8))
		if len(str) > 0 {
			return str
		}
	}

	return ""
}

//export RedisTest1
func RedisTest1() {
	Debug.Println("enter RedisTest1!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
}

//export RedisTest2
func RedisTest2() {
	Debug.Println("enter RedisTest2!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
}

func main() {
	app := "TestDlg"
	if !RedisInit("tcp", "127.0.0.1", "6379") {
		return
	}
	for {
		str := RdisGet(app)
		if len(str) == 0 {
			time.Sleep(time.Duration(10) * time.Microsecond)
			continue
		}
		index := strings.Index(str, "=")
		if index < 0 {
			continue
		}
		filename := "/home/log/" + app + "-" + str[0:index] + "-" + time.Now().Format("2006-01-02")
		f, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
		if err != nil {
			fmt.Println(err.Error())
			return
		}
		f.Write([]byte(str[index:]))
		f.Close()
	}

	RedisExit()
}
